package com.example.h9iserver.service.springAi.chatMemory;

import com.example.h9iserver.service.springAi.advisors.MyLoggerAdvisor;
import com.example.h9iserver.service.springAi.advisors.ReReadingAdvisor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Slf4j
@Service
public class FileBasedChatMemoryChatService {

//    private String systemMessage = "你是一名恋爱专家";
    private ChatMemory chatMemory;

    private ChatClient chatClient;

    public FileBasedChatMemoryChatService(ChatClient.Builder builder, @Value("classpath:/prompts/system-message-01.st") Resource systemMessage) {
        String fileDri = System.getProperty("user.dir") + "/chat-memory";
        chatMemory = new FileBasedChatMemory(fileDri);
        chatClient = builder.defaultSystem(systemMessage)
                .defaultAdvisors(new MessageChatMemoryAdvisor(chatMemory),
                        new ReReadingAdvisor(),
                        new MyLoggerAdvisor())
                .build();
    }

    /**
     * 多轮对话示例
     *
     * @param conversationId 会话id
     * @param userText 用户提示词
     */
    public void multiRoundConversation(String conversationId, String userText) {
        chatClient.prompt()
                .advisors(advisor -> advisor.param(CHAT_MEMORY_CONVERSATION_ID_KEY, conversationId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 3))
                .user(userText)
                .call()
                .content();
    }

    public List<Message> searchMessage(String conversationId) {
        return chatMemory.get(conversationId, 10);
    }
}
